package com.quktzhuanka.app.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.quktzhuanka.app.R;
import com.quktzhuanka.app.adapter.TaobaoQgAdapter;
import com.quktzhuanka.app.base.BaseActivity;
import com.quktzhuanka.app.bean.PddClient;
import com.quktzhuanka.app.bean.TaobaoQgBean;
import com.quktzhuanka.app.config.Constants;
import com.quktzhuanka.app.https.HttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

public class TqgNewActivity extends BaseActivity {
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rb_one)
    RadioButton rb1;
    @BindView(R.id.rb_two)
    RadioButton rb2;
    @BindView(R.id.rb_three)
    RadioButton rb3;
    @BindView(R.id.rb_four)
    RadioButton rb4;
    @BindView(R.id.rb_five)
    RadioButton rb5;
    @BindView(R.id.rb_six)
    RadioButton rb6;
    @BindView(R.id.rg_index)
    RadioGroup rgIndex;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    private TextView txt1, txt2, txt3;
    private static boolean flag = true;
    private int page=1;
    Date endTime;
    DateFormat df_date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private List<TaobaoQgBean> taobaoQgBeans=new ArrayList<>();
    TaobaoQgAdapter tqgAdapter;
    @Override
    protected void initUI() {
        setContentView(R.layout.activity_tqg);
        ButterKnife.bind(this);
    }

    @Override
    protected void initData() {
        tvLeft.setVisibility(View.VISIBLE);
        tvTitle.setText("限时秒杀");
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this,LinearLayoutManager.VERTICAL));
        tqgAdapter=new TaobaoQgAdapter(R.layout.index_item2,taobaoQgBeans);
        recyclerView.setAdapter(tqgAdapter);
        txt1 = findViewById(R.id.txt_hour);
        txt2 = findViewById(R.id.txt_minutes);
        txt3 = findViewById(R.id.txt_sec);
        Calendar ca = Calendar.getInstance();
        int hour = ca.get(Calendar.HOUR_OF_DAY);//小时
        int year = ca.get(Calendar.YEAR);//获取年份
        int month = ca.get(Calendar.MONTH) + 1;//获取月份
        int day = ca.get(Calendar.DATE);//获取日
        Log.d("dfasdf", year + "" + month + day);
        if (hour < 10) {
            rb1.setText(String.format(getResources().getString(R.string.test_text), "00:00", "抢购中"));
            rb1.setChecked(true);
            try {
                endTime = df_date.parse(year + "-" + month + "-" + day +" 10:00:00");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            rb1.setTextColor(getResources().getColor(R.color.white));
            rb2.setText(String.format(getResources().getString(R.string.test_text), "10:00", "即将开始"));
            rb3.setText(String.format(getResources().getString(R.string.test_text), "12:00", "即将开始"));
            rb4.setText(String.format(getResources().getString(R.string.test_text), "15:00", "即将开始"));
            rb5.setText(String.format(getResources().getString(R.string.test_text), "20:00", "即将开始"));
            rb6.setText(String.format(getResources().getString(R.string.test_text), "24:00", "即将开始"));
        } else if (hour < 12) {
            rb1.setText(String.format(getResources().getString(R.string.test_text), "00:00", "已结束"));
            rb2.setChecked(true);
            try {
                endTime = df_date.parse(year + "-" + month + "-" + day + " 12:00:00");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            rb2.setTextColor(getResources().getColor(R.color.white));
            rb2.setText(String.format(getResources().getString(R.string.test_text), "10:00", "抢购中"));
            rb3.setText(String.format(getResources().getString(R.string.test_text), "12:00", "即将开始"));
            rb4.setText(String.format(getResources().getString(R.string.test_text), "15:00", "即将开始"));
            rb5.setText(String.format(getResources().getString(R.string.test_text), "20:00", "即将开始"));
            rb6.setText(String.format(getResources().getString(R.string.test_text), "24:00", "即将开始"));
        } else if (hour < 15) {
            rb1.setText(String.format(getResources().getString(R.string.test_text), "00:00", "已结束"));
            rb3.setChecked(true);
            rb3.setTextColor(getResources().getColor(R.color.white));
            try {
                endTime = df_date.parse(year + "-" + month + "-" + day + " 15:00:00");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            rb2.setText(String.format(getResources().getString(R.string.test_text), "10:00", "已结束"));
            rb3.setText(String.format(getResources().getString(R.string.test_text), "12:00", "抢购中"));
            rb4.setText(String.format(getResources().getString(R.string.test_text), "15:00", "即将开始"));
            rb5.setText(String.format(getResources().getString(R.string.test_text), "20:00", "即将开始"));
            rb6.setText(String.format(getResources().getString(R.string.test_text), "24:00", "即将开始"));
        } else if (hour < 20) {
            rb1.setText(String.format(getResources().getString(R.string.test_text), "00:00", "已结束"));
            rb4.setChecked(true);
            rb4.setTextColor(getResources().getColor(R.color.white));
            rb2.setText(String.format(getResources().getString(R.string.test_text), "10:00", "已结束"));
            try {
                endTime = df_date.parse(year + "-" + month + "-" + day + " 20:00:00");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            rb3.setText(String.format(getResources().getString(R.string.test_text), "12:00", "已结束"));
            rb4.setText(String.format(getResources().getString(R.string.test_text), "15:00", "抢购中"));
            rb5.setText(String.format(getResources().getString(R.string.test_text), "20:00", "即将开始"));
            rb6.setText(String.format(getResources().getString(R.string.test_text), "24:00", "即将开始"));
        } else if (hour < 24) {
            rb1.setText(String.format(getResources().getString(R.string.test_text), "00:00", "已结束"));
            rb5.setChecked(true);
            try {
                endTime = df_date.parse(year + "-" + month + "-" + day + " 24:00:00");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            rb5.setTextColor(getResources().getColor(R.color.white));
            rb2.setText(String.format(getResources().getString(R.string.test_text), "10:00", "已结束"));
            rb3.setText(String.format(getResources().getString(R.string.test_text), "12:00", "已结束"));
            rb4.setText(String.format(getResources().getString(R.string.test_text), "15:00", "已结束"));
            rb5.setText(String.format(getResources().getString(R.string.test_text), "20:00", "抢购中"));
            rb6.setText(String.format(getResources().getString(R.string.test_text), "24:00", "即将开始"));
        }
        setTimer();
        getTbkListRequst1();
        tqgAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("num_iid", taobaoQgBeans.get(position).num_iid);
                openActivity(PromotionDetailsActivity.class, bundle);
            }
        });
        rgIndex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                page=1;
                getTbkListRequst1();
            }
        });
    }
    private void getTbkListRequst1(){
        Calendar ca = Calendar.getInstance();
        int hour = ca.get(Calendar.HOUR_OF_DAY);//小时
        int year = ca.get(Calendar.YEAR);//获取年份
        int month1 = ca.get(Calendar.MONTH) + 1;//获取月份
        int day1 = ca.get(Calendar.DATE);//获取日
        String month=month1<10?"0"+month1:month1+"";
        String day=day1<10?"0"+day1:day1+"";
        String start_time="",end_time="";
        if(rb1.isChecked()){
            start_time=year + "-" + month + "-" + day+" 00:00:00";
            end_time=year + "-" + month + "-" + day+" 10:00:00";
        }
        if(rb2.isChecked()){
            start_time=year + "-" + month + "-" + day+" 10:00:00";
            end_time=year + "-" + month + "-" + day+" 12:00:00";
        }
        if(rb3.isChecked()){
            start_time=year + "-" + month + "-" + day+" 12:00:00";
            end_time=year + "-" + month + "-" + day+" 15:00:00";
        }
        if(rb4.isChecked()){
            start_time=year + "-" + month + "-" + day+" 15:00:00";
            end_time=year + "-" + month + "-" + day+" 20:00:00";
        }
        if(rb5.isChecked()){
            start_time=year + "-" + month + "-" + day+" 20:00:00";
            end_time=year + "-" + month + "-" + day+" 24:00:00";
        }
        if(rb6.isChecked()){
            ca.add(Calendar.DAY_OF_MONTH, 1);
            year = ca.get(Calendar.YEAR);//获取年份
             month1 = ca.get(Calendar.MONTH) + 1;//获取月份
             day1 = ca.get(Calendar.DATE);//获取日
            month=month1<10?"0"+month1:month1+"";
            day=day1<10?"0"+day1:day1+"";
            start_time=year + "-" + month + "-" + day+" 00:00:00";
            end_time=year + "-" + month + "-" + day+" 10:00:00";
        }
        Log.d("dfasd",start_time);
        String time = new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date());
        RequestParams requestParams = new RequestParams();
        requestParams.put("method", "taobao.tbk.ju.tqg.get");
        requestParams.put("app_key", Constants.qd_app_key);
        requestParams.put("format", "json");
        requestParams.put("page_no", page);
        requestParams.put("page_size", "10");
        requestParams.put("timestamp", time);
        requestParams.put("v", "2.0");
        requestParams.put("adzone_id",Constants.ADZONE_ID);
        requestParams.put("fields","click_url,pic_url,reserve_price,zk_final_price,total_amount,sold_num,title,category_name,start_time,end_time");
        requestParams.put("start_time",start_time);
        requestParams.put("end_time",end_time);
        requestParams.put("sign_method", "md5");
        Map<String, String> temp = new HashMap<>();
        temp.put("method", "taobao.tbk.ju.tqg.get");
        temp.put("app_key", Constants.qd_app_key);
        temp.put("format", "json");
        temp.put("timestamp", time);
        temp.put("page_no", page+"");
        temp.put("page_size", "10");
        temp.put("adzone_id",Constants.ADZONE_ID);
        temp.put("fields","click_url,pic_url,reserve_price,zk_final_price,total_amount,sold_num,title,category_name,start_time,end_time");
        temp.put("start_time",start_time);
        temp.put("end_time",end_time);
        temp.put("v", "2.0");
        temp.put("sign_method", "md5");
        String sign = null;
        sign = PddClient.getSign3(temp, Constants.qd_app_secret);
        requestParams.put("sign", sign);
        HttpUtils.post1("https://eco.taobao.com/router/rest", requestParams, new TextHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("q1eqweqwe",responseString);
                try {
                    JSONObject jsonObject=new JSONObject(responseString);
                    if(page==1){
                        taobaoQgBeans.clear();
                    }
                    JSONArray array=jsonObject.getJSONObject("tbk_ju_tqg_get_response").getJSONObject("results").getJSONArray("results");
                    for(int i=0;i<array.length();i++){
                        taobaoQgBeans.add(new Gson().fromJson(array.getJSONObject(i).toString(), TaobaoQgBean.class));
                    }
                    tqgAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private void setTimer() {
        Message message = mHandler.obtainMessage(999);     // Message
        mHandler.sendMessageDelayed(message, 1000);
    }
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 999:
                    //在这里去执行定时操作逻辑
                    if (flag) {
                        long diff = endTime.getTime() - new Date().getTime();
                        long days = diff / (1000 * 60 * 60 * 24);
                        long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
                        long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);
                        long secs = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60) - minutes * (1000 * 60)) / (1000);
                        txt1.setText("0" + hours + "");
                        txt2.setText(minutes < 10 ? "0" + minutes : minutes + "");
                        txt3.setText(secs < 10 ? "0" + secs : secs + "");
                        Message message = mHandler.obtainMessage(999);
                        mHandler.sendMessageDelayed(message, 1000);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    private void stopTimer() {
        flag = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();
    }

    @Override
    protected void initListener() {
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getTbkListRequst1();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page=1;
                getTbkListRequst1();
            }
        });
    }
    @OnClick({R.id.tv_left, R.id.rb_one, R.id.rb_two, R.id.rb_three, R.id.rb_four, R.id.rb_five, R.id.rb_six, R.id.rg_index})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_left:
                finish();
                break;
            case R.id.rb_one:
            case R.id.rb_two:
            case R.id.rb_three:
            case R.id.rb_four:
            case R.id.rb_five:
            case R.id.rb_six:
                break;
            case R.id.rg_index:
                break;
        }
    }
}
